package com.shiqupad.order.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.shiqupad.order.R;
import com.shiqupad.order.activity.GetMessageTwoActivity;
import com.shiqupad.order.listener.GetAllTableListener;
import com.shiqupad.order.listener.QrCodeTableListener;
import com.shiqupad.order.presenter.GetAllTablePresenter;
import com.shiqupad.order.presenter.QrcodeTablePresenter;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.dreamtouch.common.DTLog;
import cn.com.dreamtouch.magicbox_common.util.CommonConstant;
import cn.com.dreamtouch.magicbox_general_ui.activity.ScanCodeActivity;
import cn.com.dreamtouch.magicbox_general_ui.fragment.MBBaseFragment;
import cn.com.dreamtouch.magicbox_general_ui.util.RxBusUtil;
import cn.com.dreamtouch.magicbox_http_client.network.model.GetAllTableResponse;
import cn.com.dreamtouch.magicbox_http_client.network.model.QrCodeTableResponse;
import cn.com.dreamtouch.magicbox_http_client.network.model.RxEvent;
import cn.com.dreamtouch.magicbox_repository.datasource.local.UserLocalData;
import cn.com.dreamtouch.magicbox_repository.datasource.remote.UserRemoteData;
import cn.com.dreamtouch.magicbox_repository.repository.UserRepository;
import io.reactivex.functions.Consumer;
import rx.functions.Action1;

/**
 * Created by LuoXueKun
 * on 2018/5/14
 */
public class TableScanFragment extends MBBaseFragment implements OnTabSelectListener, GetAllTableListener, QrCodeTableListener {

    public final static int REQUESR_SCAN = 0xe3;//扫码开台
    private static final int REQ_CODE_PERMISSION = 250;
    @Bind(R.id.ct_main_stl)
    SlidingTabLayout mSlidingTabLayout;
    @Bind(R.id.fr_table_scan_vp)
    ViewPager mViewPager;
    @Bind(R.id.ct_main_scan)
    LinearLayout ctMainScan;

    @Bind(R.id.content_foot_free_ll)
    LinearLayout mFreeLl;
    @Bind(R.id.content_foot_order_ll)
    LinearLayout mOrderLl;
    @Bind(R.id.content_foot_finish_ll)
    LinearLayout mFinishLl;
    @Bind(R.id.content_foot_disable_ll)
    LinearLayout mDisableLl;
    @Bind(R.id.content_foot_message_iv)
    ImageView mMessageIv;
    @Bind(R.id.content_foot_all_ll)
    LinearLayout mAllLl;
    @Bind(R.id.cont_main_foot_ll)
    RelativeLayout mFootMessageLl;
    @Bind(R.id.iv_message_tip)
    ImageView ivMessageTip;
    private View view;
    private GetAllTablePresenter getAllTablePresenter;
    private QrcodeTablePresenter qrcodeTablePresenter;
    private String mSid;
    private String mShopID;

    public ArrayList<GetAllTableResponse.Data> mAllTableDataList;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private List<String> mTitleList;
    private MyPagerAdapter mAdapter;

    String code;

    private int messageAccount;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        getAllTablePresenter.unSubscribe();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    public TableScanFragment() {
    }

    public static TableScanFragment newInstance() {
        TableScanFragment fragment = new TableScanFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initVariables() {
        super.initVariables();


        mSid = UserLocalData.getInstance(getActivity()).getSid();
        mShopID = UserLocalData.getInstance(getActivity()).getShopID();
        mTitleList = new ArrayList<>();
        mAllTableDataList = new ArrayList<>();
        getAllTablePresenter = new GetAllTablePresenter(UserRepository.getInstance(UserLocalData.getInstance(getActivity())
                , UserRemoteData.getInstance(getActivity())), this);
        qrcodeTablePresenter = new QrcodeTablePresenter(UserRepository.getInstance(UserLocalData.getInstance(getActivity())
                , UserRemoteData.getInstance(getActivity())), this);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fr_table_scan, container, false);
        ButterKnife.bind(this, view);
        getRxEvent();
        return view;

    }

    public void refreshTabData() {

    }

    @Override
    protected void loadData() {
        super.loadData();
        getAllTablePresenter.getAllTable(mSid, mShopID, "1");
    }


    @Override
    public void onTabSelect(int position) {

    }

    @Override
    public void onTabReselect(int position) {

    }

    @Override
    public void getAllTableSuccess(GetAllTableResponse getAllTableResponse) {

        List<GetAllTableResponse.Data> data = getAllTableResponse.getData();
        mAllTableDataList.clear();
        mAllTableDataList.addAll(data);
        mTitleList.clear();
        mTitleList.add("全部");
        mFragments.clear();
        mFragments.add(TableFragment.newInstance(-1));
        for (int i = 0; i < data.size(); i++) {
            String areaName = data.get(i).getAreaName();
            mTitleList.add(areaName);
            TableFragment tableFragment = TableFragment.newInstance(data.get(i).getAreaID());
            mFragments.add(tableFragment);
        }
        initTabAndView();

    }


    private void initTabAndView() {
        mAdapter = new MyPagerAdapter(getChildFragmentManager());
        mViewPager.setAdapter(mAdapter);
        mSlidingTabLayout.setViewPager(mViewPager);
        mSlidingTabLayout.setOnTabSelectListener(this);
        mViewPager.setCurrentItem(0);
        mViewPager.setOffscreenPageLimit(mAllTableDataList.size());
    }

    @Override
    public void basicFailure(String prompt) {
        DTLog.showMessageShort(getActivity(), prompt);
    }

    @Override
    public void qrcodeTableSuccess(QrCodeTableResponse qrcodeTableResponse) {
        if (qrcodeTableResponse.getData().getStatus() == 1) {
            RxBusUtil.getDefault().post(new RxEvent(CommonConstant.OpertionType.QRCODE_TABLE_SUCCESS
                    ,
                    qrcodeTableResponse.getData().getTableID()));
        } else {
            DTLog.showMessageShort(getActivity(), "该桌台已被占用");
        }
    }

    public void getRxEvent() {
        RxBusUtil.getDefault().toObservable(RxEvent.class).subscribe(new Action1<RxEvent>() {
            @Override
            public void call(RxEvent rxEvent) {
                switch (rxEvent.getFlag()) {
                    case CommonConstant.OpertionType.PUSH_MESSAGE:
                        messageAccount++;
                        refreshBageView();
                        break;
                    case CommonConstant.OpertionType.HAS_READ_MESSAGE:
                        messageAccount = 0;
                        if(ivMessageTip != null){
                            ivMessageTip.setVisibility(View.GONE);
                        }

                        break;
                }
            }
        });
    }

    private void refreshBageView() {

        if (ivMessageTip != null) {
            ivMessageTip.setVisibility(View.VISIBLE);
        }
    }


    private class MyPagerAdapter extends FragmentPagerAdapter {
        private MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position);
        }

        @Override
        public Fragment getItem(int position) {


            return mFragments.get(position);

        }
    }

    @OnClick({R.id.content_foot_free_ll, R.id.content_foot_disable_ll,
            R.id.content_foot_order_ll, R.id.content_foot_finish_ll,
            R.id.cont_main_foot_ll, R.id.content_foot_all_ll, R.id.ct_main_scan})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.content_foot_free_ll:
                RxBusUtil.getDefault().post(new RxEvent(CommonConstant.TableStatus.FREE, 1));
                break;
            case R.id.content_foot_disable_ll:
                RxBusUtil.getDefault().post(new RxEvent(CommonConstant.TableStatus.DISABLE, 0));
                break;
            case R.id.content_foot_order_ll:
                RxBusUtil.getDefault().post(new RxEvent(CommonConstant.TableStatus.OCCUPY, 2));
                break;
            case R.id.content_foot_finish_ll:
                RxBusUtil.getDefault().post(new RxEvent(CommonConstant.TableStatus.INVOICING, 4));
                break;
            case R.id.cont_main_foot_ll:
                startActivity(new Intent(getActivity(), GetMessageTwoActivity.class));
               // Objects.requireNonNull(getActivity()).overridePendingTransition(R.anim.activity_open, R.anim.activity_close);
                break;
            case R.id.content_foot_all_ll:
                RxBusUtil.getDefault().post(new RxEvent(CommonConstant.TableStatus.ALL, -10));
                break;
            case R.id.ct_main_scan:

                openCameraWithPermission();
                break;
            default:
                break;
        }
    }

    private boolean askedPermission = false;


  /*  private void openCameraWithPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            //jump2ActivityForResult(ScanCodeActivity.class, REQUESR_SCAN);
            goToScanActivity();
        } else if (!askedPermission) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.CAMERA},
                    REQ_CODE_PERMISSION);
            askedPermission = true;
        } else {
            // Wait for permission result
        }
    }*/
    @SuppressLint("CheckResult")
    @TargetApi(23)
    private void openCameraWithPermission() {
        RxPermissions rxPermission = new RxPermissions(Objects.requireNonNull(getActivity()));
        rxPermission.requestEach(
                Manifest.permission.CAMERA
        ).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                if (permission.granted) {
                    // 用户已经同意该权限
                    goToScanActivity();
                } else if (permission.shouldShowRequestPermissionRationale) {

                } else {
                     DTLog.showMessage(getActivity(),"请到应用设置中打开相机权限");
                }
            }
        });
    }


    private void goToScanActivity() {
        //假如你要用的是fragment进行界面的跳转
        IntentIntegrator intentIntegrator = IntentIntegrator.forSupportFragment(TableScanFragment.this).
                setCaptureActivity(ScanCodeActivity.class);
        //IntentIntegrator intentIntegrator = new IntentIntegrator(getActivity());
        intentIntegrator
                .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
                .setPrompt("将二维码/条码放入框内，即可自动扫描")//写那句提示的话
                .setOrientationLocked(false)//扫描方向固定
                .setCaptureActivity(ScanCodeActivity.class) // 设置自定义的activity是CustomActivity
                .initiateScan(); // 初始化扫描
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mLogger.e("onActivityResult");
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null) {
            if (intentResult.getContents() == null) {
            } else {
                // ScanResult 为获取到的字符串
                String scanResult = intentResult.getContents();
                code = scanResult.substring(scanResult.length() - 6, scanResult.length());
                requestGetTableByID(code);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    //通过二维码获取桌台
    private void requestGetTableByID(String qrCode) {
        qrcodeTablePresenter.qrcodeTable(mShopID, qrCode);
    }
}
